﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DimensionData.Data2;

namespace DimensionAddIn
{
    public class DocData
    {
        public ExcelDataRect VisualRect { get; set; }
        public DocValueTable ValueTable { get; set; }

        public List<DataRefItem> DataRefList { get; set; }

        public DTree YTree { get; set; }
        public DTree XTree { get; set; }

        public DocData(DTree yTree, DTree xTree, List<PageDim> pageDim)
        {
            YTree = yTree;
            XTree = xTree;

            VisualRect = new ExcelDataRect();
            ValueTable = new DocValueTable();
            DataRefList = new List<DataRefItem>();
        }

        /// <summary>
        /// 通过完成的维度路径来计算，在目前的显示情况下，该路径所处的单元格位置
        /// 1.将路径拆分
        /// 2.按照行维来定位 行
        /// 3.按照列维来定位 列
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public ExcelPos GetXlsPos(string path)
        {
            string[] segements = path.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries);
            string rowPath = "";
            string colPath = "";
            int yCount = YTree.Table.Tables.Count;
            int xCount = XTree.Table.Tables.Count;
            for (int index = 0; index < yCount; index++)
            {
                rowPath += @"\";
                rowPath += segements[index];
            }
            for (int index = 0; index < xCount; index++)
            {
                colPath += @"\";
                colPath += segements[yCount + index];
            }

            List<DRow> yRows = YTree.Complanate2();
            List<DRow> xRows = XTree.Complanate2();

            int? hitRow = null;
            int? hitCol = null;
            for (int yIndex = 0; yIndex < VisualRect.YRowIndexList.Count; yIndex++)
            {
                DRow yRow = yRows[VisualRect.YRowIndexList[yIndex]];

                string yRowPath = yRow.GetCodePath();
                if (rowPath == yRowPath)
                {
                    hitRow = yIndex;
                    break;
                }
            }

            for (int xIndex = 0; xIndex < VisualRect.XRowIndexList.Count; xIndex++)
            {
                DRow xRow = xRows[VisualRect.XRowIndexList[xIndex]];
                string xRowPath = xRow.GetCodePath();
                if (colPath == xRowPath)
                {
                    hitCol = xIndex;
                    break;
                }
            }

            if (hitRow != null && hitCol != null)
            {
                return new ExcelPos(VisualRect.DataBeginRow + hitRow.Value, VisualRect.DataBeginCol + hitCol.Value);
            }
            return null;
        }
    }
}
